import * as auth from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: auth.getToken() || null,
    userInfo: {}
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      auth.setToken(token)
    },
    delToken (state) {
      state.token = null
      auth.removeToken()
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    delUserInfo (state) {
      state.userInfo = {}
    }
  },
  actions: {
    logout ({ commit }) {
      // 前端退出 删除数据
      commit('delToken')
      commit('delUserInfo')
      // 后端退出 发请求
    },
    async getUserInfoAction ({ commit }) {
      const data = await getUserInfo()
      const res = await getUserDetailById(data.userId)
      commit('setUserInfo', { ...data, ...res })
    },
    async login ({ commit }, formData) {
      const res = await login(formData)
      commit('setToken', res)
    }
  }
}

